package com.jqsoft.launcher.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Environment;
import android.telephony.TelephonyManager;

import com.jqsoft.launcher.activity.bean.DictionaryBean;
import com.jqsoft.launcher.dictionarydb.DataDictionaryDao;

import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 公共方法处理
 * 
 * @author gujunqi date：2013-12-24
 */
public class CommonUtil {
	static DecimalFormat fmt = new DecimalFormat("##,###,###,##0.00");

	// private static String tag = "CommonUtil";
	// 是否显示错误提示
	// private static int showErrorSign;

	/**
	 * 判断集合是否不为空
	 * 
	 * @param collection
	 * @return 集合不为空返回true，否则返回false
	 */
	@SuppressWarnings("rawtypes")
	public static boolean isCollectionNotEmpty(Collection collection) {
		if (collection != null && collection.size() > 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 判断字符串是否不为空
	 * 
	 * @param value
	 * @return 字符串不为空返回true，否则返回false
	 */
	public static boolean isStringNotEmpty(String value) {

		if (value != null && !"".equals(value)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 判断字符串是否空
	 * 
	 * @param value
	 * @return 字符串不为空返回true，否则返回false
	 */
	public static boolean isStringEmpty(String value) {

		return !isStringNotEmpty(value);
	}

	public static DefaultHttpClient getHttpClient() {
		HttpParams httpParameters = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParameters, 8000);
		HttpConnectionParams.setSoTimeout(httpParameters, 32000);
		return new DefaultHttpClient(httpParameters);
	}

	public static String trimStringByLength(String s, int length) {
		if (s.length() <= length) {
			return s;
		} else {
			return s.substring(0, length - 1) + "...";
		}
	}

	/*
	 * 获取手机序列号
	 */
	public static String getDeviceId(Context ctx) {
		String deviceID = "";
		TelephonyManager tm = (TelephonyManager) ctx
				.getSystemService(Context.TELEPHONY_SERVICE);
		if (tm.getDeviceId() != null) {
			deviceID = tm.getDeviceId();
			Log.d("UTIL", "deviceID:" + deviceID);
		}
		return deviceID;
	}

	/**
	 * 将输入字符串流转换为字符串
	 * 
	 * @param in
	 *            输入字符串流
	 * @return
	 * @throws IOException
	 */
	public static String inputStream2String(InputStream is) throws IOException {
		// 为了将InputStream转换成String我们使用函数BufferedReader.readLine().
		// 我们迭代调用BufferedReader直到其返回null, null意味着没有其他的数据要读取了.
		// 每一行将会追加到StringBuilder的末尾, StringBuilder将作为String返回。
		if (is != null) {
			StringBuilder sb = new StringBuilder();
			String line;
			try {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "UTF-8"));
				while ((line = reader.readLine()) != null) {
					sb.append(line).append("\n");
				}
			} finally {
				is.close();
			}
			return sb.toString();
		} else {
			return "";
		}
	}

	/**
	 * 检查Internet是否可以正常连接
	 * 
	 * @param ctx
	 * @return
	 */
	public static boolean checkNetWorkStatus(Context ctx) {
		boolean netSataus = false;
		ConnectivityManager cwjManager = (ConnectivityManager) ctx
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		cwjManager.getActiveNetworkInfo();
		if (cwjManager.getActiveNetworkInfo() != null) {
			netSataus = cwjManager.getActiveNetworkInfo().isAvailable();
		}
		return netSataus;
	}

	/**
	 * 本地缓存目录
	 * 
	 * @return
	 */
	public static String getCachePath(Context ctx) {
		File sdDir = null;
		// 判断SDCard是否存在
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
		// 存在SDCard
		if (sdCardExist) {
			// 获取外部存储目录即 SDCard 根目录
			sdDir = Environment.getExternalStorageDirectory();
		} else {
			// 应用缓存目录
			sdDir = ctx.getCacheDir();
		}
		return sdDir.toString() + "/SPD_PRODUCT_IMAGE_CACHE/";

	}

	// 字符串转换成int
	public static int string2Int(String s) {
		if (s == null || "".equals(s))
			return 0;
		int result = 0;
		try {
			result = Integer.parseInt(s);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	// 1---安全强度低(纯数字、纯字母) 2---安全强度中(字母+数字、字母+特殊字符、数字+特殊字符)
	// 3---安全强度高(纯特殊字符、字母+数字+特殊字符)
	public static String getResult(String password) {

		Pattern p1 = Pattern.compile("\\d+|[a-zA-Z]+");
		Pattern p2 = Pattern
				.compile("([a-zA-Z]+[0-9]+)|([0-9]+[a-zA-Z]+)|([a-zA-Z]+[\\p{Punct}]+)|([\\p{Punct}]+[a-zA-Z]+)|([0-9]+[\\p{Punct}]+)|([\\p{Punct}]+[0-9]+)");
		Pattern p3 = Pattern
				.compile("[\\p{Punct}]+|([a-zA-Z]+[0-9]+[\\p{Punct}]+)|([a-zA-Z]+[\\p{Punct}]+[0-9]+)|([0-9]+[a-zA-Z]+[\\p{Punct}]+)|([0-9]+[\\p{Punct}]+[a-zA-Z]+)|([\\p{Punct}]+[a-zA-Z]+[0-9]+)|([\\p{Punct}]+[0-9]+[a-zA-Z]+)");

		Matcher m1 = p1.matcher(password);
		Matcher m2 = p2.matcher(password);
		Matcher m3 = p3.matcher(password);
		if (m1.matches()) {
			return "1";
		} else if (m2.matches()) {
			return "2";
		} else if (m3.matches()) {
			return "3";
		}
		return "0";
	}

	public static String String2date(String date) {
		if (date != "" || date != null) {
			String[] a = date.split(" ");
			// return date=date.replace("0:00:00", "").trim();
			return date = a[0];
		} else {
			return "";
		}
	}

	public static int calcAge2(String birthday) {
		int iage = 0;

		if (birthday != "" && birthday != null) {

			birthday = String2date(birthday);
			// 1905/11/1
			String splitStr = "";
			if (birthday.contains("-")) {
				splitStr = "-";
			} else {
				splitStr = "/";
			}
			int year = 0, month = 0, day = 0;
			String[] a = birthday.split(splitStr);
			if (a.length > 2) {
				year = Integer.parseInt(a[0]);

				month = Integer.parseInt(a[1]);

				day = Integer.parseInt(a[2]);
			}
			// int year = Integer.parseInt(birthday.substring(0, 4));
			// int month = Integer.parseInt(birthday.substring(4, 6));
			// int day = Integer.parseInt(birthday.substring(6,8));

			Calendar birthDate = new GregorianCalendar(year, month, day);
			Calendar today = Calendar.getInstance();

			if (today.get(Calendar.YEAR) > birthDate.get(Calendar.YEAR)) {
				iage = today.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR)
						- 1;
				if (today.get(Calendar.MONTH) + 1 > birthDate
						.get(Calendar.MONTH)) {
					iage++;
				} else if (today.get(Calendar.MONTH) + 1 == birthDate
						.get(Calendar.MONTH)) {

					if (today.get(Calendar.DAY_OF_MONTH) > birthDate
							.get(Calendar.DAY_OF_MONTH)) {
						iage++;
					}
				}
			}
			return ++iage;
		}

		return 0;
	}

	// 数据字典工具
	public static JSONObject getAllDictionary(Map<String, String> map) {
		JSONObject jsonObject = new JSONObject();
		try {
			for (String key : map.keySet()) {
				List<DictionaryBean> list = DataDictionaryDao.getGroupList(key);
				JSONArray jsonArray = new JSONArray();
				for (DictionaryBean bean : list) {
					JSONObject jsonObj = new JSONObject();
					jsonObj.put("itemName", bean.getItem_name());
					jsonObj.put("itemCode", bean.getItem_code());
					jsonArray.put(jsonObj);
				}
				jsonObject.put(map.get(key), jsonArray); // 封装集合数组
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonObject;
	}

	/**
	 * 获得全球唯一ID
	 * 
	 * @return UUID
	 */
	public static String getUUID() {
		UUID uuid = UUID.randomUUID();
		return uuid.toString();
	}

	// 获取数组中的数据以字符串返回，隔开

	public static String getIndexStr(String[] strs, int startIndex, int endIndex) {
		String result = "";
		for (int i = startIndex - 1; i >= startIndex - 1 && i < endIndex; i++) {
			if (StringTools.isEmpty(result)) {
				result = strs[i];
			} else {
				result = result + "," + strs[i];
			}
		}
		return result;
	}
}
